package com.fuelindustries.ant.jsfl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.fuelindustries.ant.FuelAntVariables;
import com.fuelindustries.ant.utils.FileUtils;
import com.fuelindustries.ant.utils.OSUtils;

public class DeleteASOFiles 
{
	private String __jsfl;
	private String __flashpath;
	private String __configdirfile;
	
	public void deleteasofiles( String flashpath )
	{
		__flashpath = flashpath;
		
		try
		{
			createJSFL();
			runJSFL();
			cleanup();
		}
		catch( Exception e )
		{
			System.out.println( e.getMessage() );
		}
	}
	
	private void createJSFL() throws IOException
	{
		__jsfl = FuelAntVariables.BASE_DIR + FuelAntVariables.TEMP_DIR + File.separator + FuelAntVariables.DELETE_ASO_JSFL;
		__configdirfile = FuelAntVariables.BASE_DIR + FuelAntVariables.TEMP_DIR + File.separator + FuelAntVariables.CONIF_DIR_FILE;
		
		FileWriter writer = new FileWriter( __jsfl );
		BufferedWriter buffer = new BufferedWriter( writer );
		buffer.write("var dir = fl.configDirectory;");
		buffer.newLine();
		buffer.write( "FLfile.write( \"file:///" + __configdirfile + "\", dir );"  );
		buffer.newLine();
		buffer.close();
	}
	
	private void runJSFL() throws IOException, InterruptedException
	{
		String[] command = new String[]{};
		if( OSUtils.isWindows() )
		{
			command = new String[]{ __flashpath, __jsfl };
		}
		else
		{
			command = new String[]{ "osascript", "-e", "tell app \"" + __flashpath + "\" to open posix file \""+ __jsfl +"\"" };
		}
		
		Process result = Runtime.getRuntime().exec( command );
        result.waitFor();
        
        File config = new File( __configdirfile );
        while( !config.exists() )
        {
        	
        }
        
        String configdir = FileUtils.getContents(config).trim() + "/Classes/aso";
       
        File asodir = new File( configdir );
        if( asodir.exists() )
        {
        	boolean success = FileUtils.deleteDirRecursive( asodir );
        	if( success )
        	{
        		System.out.println( "ASO Files deleted" );
        	}
        	else
        	{
        		System.out.println( "An Error occured while trying to delete ASO Files" );
        	}
        }
        else
        {
        	System.out.println( "ASO Files directory doesn't exist" );
        }
        
        result.destroy();
	}
	
	private void cleanup()
	{
		File jsfl = new File( __jsfl );
		while( jsfl.exists() )
		{
			jsfl.delete();
		}
		
		File config = new File( __configdirfile );
		while( config.exists() )
		{
			config.delete();
		}
	}
}
